<template>
  <div class="page-container">
    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="showAddRecordDialog">
        <el-icon><Plus /></el-icon>记录饮食
      </el-button>
      <el-button type="info" @click="showHistoryDialog">
        <el-icon><Clock /></el-icon>饮食历史
      </el-button>
    </div>

    <!-- 饮食统计图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <div class="health-card">
          <div class="card-header">
            <h3>饮食营养统计</h3>
            <div class="header-actions">
              <el-radio-group v-model="chartPeriod" @change="loadChartData">
                <el-radio-button label="week">最近一周</el-radio-button>
                <el-radio-button label="month">最近一月</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-container" ref="chartContainer"></div>
        </div>
      </el-col>
    </el-row>

    <!-- 今日营养摄入汇总 -->
    <el-row :gutter="20" class="summary-row">
      <el-col :span="24">
        <div class="health-card">
          <div class="card-header">
            <h3>今日营养摄入汇总</h3>
            <el-button type="primary" size="small" @click="refreshTodaySummary">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>

          <el-row :gutter="20">
            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">总热量</div>
                <div class="summary-value">{{ todaySummary.totalCalories }} kcal</div>
                <div class="summary-progress">
                  <el-progress
                    :percentage="todaySummary.caloriesPercentage"
                    :color="getProgressColor(todaySummary.caloriesPercentage)"
                  />
                </div>
              </div>
            </el-col>

            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">蛋白质</div>
                <div class="summary-value">{{ todaySummary.totalProtein }} g</div>
                <div class="summary-progress">
                  <el-progress
                    :percentage="todaySummary.proteinPercentage"
                    :color="getProgressColor(todaySummary.proteinPercentage)"
                  />
                </div>
              </div>
            </el-col>

            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">碳水化合物</div>
                <div class="summary-value">{{ todaySummary.totalCarbohydrate }} g</div>
                <div class="summary-progress">
                  <el-progress
                    :percentage="todaySummary.carbohydratePercentage"
                    :color="getProgressColor(todaySummary.carbohydratePercentage)"
                  />
                </div>
              </div>
            </el-col>

            <el-col :span="6">
              <div class="summary-item">
                <div class="summary-label">脂肪</div>
                <div class="summary-value">{{ todaySummary.totalFat }} g</div>
                <div class="summary-progress">
                  <el-progress
                    :percentage="todaySummary.fatPercentage"
                    :color="getProgressColor(todaySummary.fatPercentage)"
                  />
                </div>
              </div>
            </el-col>
          </el-row>

          <div class="recommendation">
            <p>
              建议每日摄入：热量 2000-2500 kcal | 蛋白质 50-60 g | 碳水化合物 250-300 g |
              脂肪 50-65 g
            </p>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 饮食记录弹窗 -->
    <el-dialog
      v-model="addRecordDialogVisible"
      title="记录饮食"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dietFormRef"
        :model="dietForm"
        :rules="dietRules"
        label-width="100px"
        class="diet-form"
      >
        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker
            v-model="dietForm.recordDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disableFutureDate"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="餐次" prop="mealType">
          <el-select
            v-model="dietForm.mealType"
            placeholder="请选择餐次"
            style="width: 100%"
          >
            <el-option label="早餐" value="1" />
            <el-option label="午餐" value="2" />
            <el-option label="晚餐" value="3" />
            <el-option label="加餐" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="食物名称" prop="foodName">
          <el-input v-model="dietForm.foodName" placeholder="请输入食物名称" />
        </el-form-item>

        <el-form-item label="食物重量" prop="weight">
          <el-input-number
            v-model="dietForm.weight"
            :min="1"
            :max="5000"
            :step="10"
            placeholder="请输入食物重量(克)"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="热量" prop="calorie">
          <el-input-number
            v-model="dietForm.calorie"
            :min="0"
            :max="5000"
            :step="5"
            placeholder="请输入热量(kcal)"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="蛋白质" prop="protein">
          <el-input-number
            v-model="dietForm.protein"
            :min="0"
            :max="500"
            :precision="1"
            :step="0.1"
            placeholder="请输入蛋白质含量(克)"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="碳水化合物" prop="carbohydrate">
          <el-input-number
            v-model="dietForm.carbohydrate"
            :min="0"
            :max="500"
            :precision="1"
            :step="0.1"
            placeholder="请输入碳水化合物含量(克)"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="脂肪" prop="fat">
          <el-input-number
            v-model="dietForm.fat"
            :min="0"
            :max="500"
            :precision="1"
            :step="0.1"
            placeholder="请输入脂肪含量(克)"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="dietForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addRecordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDietForm" :loading="submitting">
            保存记录
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 饮食历史记录弹窗 -->
    <el-dialog
      v-model="historyDialogVisible"
      title="饮食历史记录"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="history-header">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="loadHistoryRecords"
          style="margin-right: 10px"
        />
        <el-button type="primary" @click="loadHistoryRecords">
          <el-icon><Search /></el-icon>查询
        </el-button>
      </div>

      <el-table
        :data="historyRecords"
        style="width: 100%"
        v-loading="loading"
        height="400"
      >
        <el-table-column label="日期" width="150">
          <template #default="scope">
            {{ scope.row.dietDate || scope.row.recordDate }}
          </template>
        </el-table-column>
        <el-table-column label="餐次" width="150">
          <template #default="scope">
            {{ scope.row.mealType === 1 ? '早餐' : scope.row.mealType === 2 ? '午餐' : scope.row.mealType === 3 ? '晚餐' : '加餐' }}
          </template>
        </el-table-column>
        <el-table-column prop="foodName" label="食物名称" width="150" />
        <el-table-column prop="calorie" label="热量(kcal)" width="150" />
        <el-table-column prop="protein" label="蛋白质(g)" width="150" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="danger" size="small" @click="deleteRecord(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useDietStore } from "@/store/diet";
import * as echarts from "echarts";
import dayjs from "dayjs";

const dietStore = useDietStore();

const dietFormRef = ref();

// 弹窗显示状态
const addRecordDialogVisible = ref(false);
const historyDialogVisible = ref(false);

const dietForm = ref({
  recordDate: dayjs().format("YYYY-MM-DD"),
  mealType: "",
  foodName: "",
  weight: null,
  calorie: null,
  protein: null,
  carbohydrate: null,
  fat: null,
  notes: "",
});

const dietRules = {
  recordDate: [{ required: true, message: "请选择记录日期", trigger: "change" }],
  mealType: [{ required: true, message: "请选择餐次", trigger: "change" }],
  foodName: [{ required: true, message: "请输入食物名称", trigger: "blur" }],
  weight: [{ required: true, message: "请输入食物重量", trigger: "blur" }],
  calorie: [{ required: true, message: "请输入热量", trigger: "blur" }],
};

const dateRange = ref([
  dayjs().subtract(30, "day").format("YYYY-MM-DD"),
  dayjs().format("YYYY-MM-DD"),
]);

const historyRecords = ref([]);
const loading = ref(false);
const submitting = ref(false);
const chartPeriod = ref("week");
const chartContainer = ref();
let chartInstance = null;

// 显示添加记录弹窗
const showAddRecordDialog = () => {
  resetForm();
  addRecordDialogVisible.value = true;
};

// 显示历史记录弹窗
const showHistoryDialog = () => {
  // 设置默认日期范围为最近7天
  const endDate = new Date();
  const startDate = new Date();
  startDate.setDate(endDate.getDate() - 7);
  
  dateRange.value = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ];
  
  loadHistoryRecords();
  historyDialogVisible.value = true;
};

// 今日营养摄入汇总
const todaySummary = ref({
  totalCalories: 0,
  totalProtein: 0,
  totalCarbohydrate: 0,
  totalFat: 0,
  caloriesPercentage: 0,
  proteinPercentage: 0,
  carbohydratePercentage: 0,
  fatPercentage: 0,
});

// 方法
const disableFutureDate = (time) => {
  return time.getTime() > Date.now();
};

const submitDietForm = async () => {
  if (!dietFormRef.value) return;

  await dietFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        await dietStore.createRecord(dietForm.value);
        ElMessage.success("饮食记录保存成功");
        addRecordDialogVisible.value = false;
        resetForm();
        loadHistoryRecords();
        loadChartData();
        refreshTodaySummary();
      } catch (error) {
        console.error("保存饮食记录失败", error);
        ElMessage.error("保存失败，请重试");
      } finally {
        submitting.value = false;
      }
    }
  });
};

const resetForm = () => {
  if (dietFormRef.value) {
    dietFormRef.value.resetFields();
  }
  dietForm.value = {
    recordDate: dayjs().format("YYYY-MM-DD"),
    mealType: "",
    foodName: "",
    weight: null,
    calorie: null,
    protein: null,
    carbohydrate: null,
    fat: null,
    notes: "",
  };
};

const loadHistoryRecords = async () => {
  if (!dateRange.value || dateRange.value.length !== 2) return;

  loading.value = true;
  try {
    const [startDate, endDate] = dateRange.value;
    const response = await dietStore.getRecordsByDateRange(startDate, endDate);
    historyRecords.value = response || [];
  } catch (error) {
    console.error("加载饮食历史记录失败", error);
    ElMessage.error("加载历史记录失败");
  } finally {
    loading.value = false;
  }
};

const editRecord = (record) => {
  dietForm.value = { ...record };
};

const deleteRecord = async (record) => {
  try {
    await ElMessageBox.confirm("确定要删除这条记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });



    await dietStore.deleteRecord(record.dietId);
    ElMessage.success("删除成功");
    loadHistoryRecords();
    loadChartData();
    refreshTodaySummary();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除记录失败", error);
      ElMessage.error("删除失败，请重试");
    }
  }
};

const loadChartData = async () => {
  try {
    let startDate, endDate;

    if (chartPeriod.value === "week") {
      startDate = dayjs().subtract(7, "day").format("YYYY-MM-DD");
      endDate = dayjs().format("YYYY-MM-DD");
    } else {
      startDate = dayjs().subtract(30, "day").format("YYYY-MM-DD");
      endDate = dayjs().format("YYYY-MM-DD");
    }

    const response = await dietStore.getRecordsByDateRange(startDate, endDate);
    const records = response || [];

    // 按日期分组统计
    const dateMap = {};
    records.forEach((record) => {
      // 使用正确的字段名 dietDate 而不是 recordDate
      const recordDate = record.dietDate || record.recordDate;
      if (!dateMap[recordDate]) {
        dateMap[recordDate] = {
          calories: 0,
          protein: 0,
          carbohydrate: 0,
          fat: 0,
        };
      }
      dateMap[recordDate].calories += record.calorie || 0;
      dateMap[recordDate].protein += record.protein || 0;
      dateMap[recordDate].carbohydrate += record.carbohydrate || 0;
      dateMap[recordDate].fat += record.fat || 0;
    });

    // 生成图表数据
    const dates = [];
    const calories = [];
    const protein = [];
    const carbohydrate = [];
    const fat = [];

    // 填充所有日期（包括没有数据的日期）
    const start = dayjs(startDate);
    const end = dayjs(endDate);
    let current = start;

    while (current.isBefore(end) || current.isSame(end)) {
      const dateStr = current.format("YYYY-MM-DD");
      dates.push(current.format("MM-DD"));

      if (dateMap[dateStr]) {
        calories.push(dateMap[dateStr].calories);
        protein.push(dateMap[dateStr].protein);
        carbohydrate.push(dateMap[dateStr].carbohydrate);
        fat.push(dateMap[dateStr].fat);
      } else {
        calories.push(0);
        protein.push(0);
        carbohydrate.push(0);
        fat.push(0);
      }

      current = current.add(1, "day");
    }

    // 渲染图表
    renderChart(dates, calories, protein, carbohydrate, fat);
  } catch (error) {
    console.error("加载图表数据失败", error);
  }
};

const renderChart = (dates, calories, protein, carbohydrate, fat) => {
  if (!chartContainer.value) return;

  if (chartInstance) {
    chartInstance.dispose();
  }

  chartInstance = echarts.init(chartContainer.value);

  const option = {
    title: {
      text: "营养成分摄入趋势",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
    },
    legend: {
      data: ["热量(kcal)", "蛋白质(g)", "碳水化合物(g)", "脂肪(g)"],
      top: 30,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "热量(kcal)",
        type: "line",
        data: calories,
        smooth: true,
        itemStyle: {
          color: "#5470c6",
        },
      },
      {
        name: "蛋白质(g)",
        type: "line",
        data: protein,
        smooth: true,
        itemStyle: {
          color: "#91cc75",
        },
      },
      {
        name: "碳水化合物(g)",
        type: "line",
        data: carbohydrate,
        smooth: true,
        itemStyle: {
          color: "#fac858",
        },
      },
      {
        name: "脂肪(g)",
        type: "line",
        data: fat,
        smooth: true,
        itemStyle: {
          color: "#ee6666",
        },
      },
    ],
  };

  chartInstance.setOption(option);
};

const refreshTodaySummary = async () => {
  try {
    const today = dayjs().format("YYYY-MM-DD");
    const response = await dietStore.getRecords(today);
    const records = response || [];

    // 计算今日营养摄入总量
    let totalCalories = 0;
    let totalProtein = 0;
    let totalCarbohydrate = 0;
    let totalFat = 0;

    records.forEach((record) => {
      totalCalories += record.calorie || 0;
      totalProtein += record.protein || 0;
      totalCarbohydrate += record.carbohydrate || 0;
      totalFat += record.fat || 0;
    });

    // 计算百分比（基于推荐摄入量）
    const caloriesPercentage = Math.min(Math.round((totalCalories / 2250) * 100), 100);
    const proteinPercentage = Math.min(Math.round((totalProtein / 55) * 100), 100);
    const carbohydratePercentage = Math.min(
      Math.round((totalCarbohydrate / 275) * 100),
      100
    );
    const fatPercentage = Math.min(Math.round((totalFat / 57.5) * 100), 100);

    todaySummary.value = {
      totalCalories,
      totalProtein,
      totalCarbohydrate,
      totalFat,
      caloriesPercentage,
      proteinPercentage,
      carbohydratePercentage,
      fatPercentage,
    };
  } catch (error) {
    console.error("获取今日营养摄入汇总失败", error);
  }
};

const getProgressColor = (percentage) => {
  if (percentage < 70) return "#67c23a";
  if (percentage < 90) return "#e6a23c";
  return "#f56c6c";
};

// 生命周期
onMounted(async () => {
  await loadHistoryRecords();
  await nextTick();
  loadChartData();
  refreshTodaySummary();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #2c3e50;
  font-weight: 600;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.diet-form {
  padding: 10px 0;
}

.chart-row,
.summary-row {
  margin-top: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.summary-item {
  text-align: center;
  padding: 10px;
}

.summary-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.summary-progress {
  margin-bottom: 5px;
}

.recommendation {
  margin-top: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 6px;
  text-align: center;
  color: #606266;
  font-size: 14px;
}

.history-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
</style>
